package top.korori.common.utils;

import org.springframework.util.StringUtils;
import top.korori.common.func.Func1;

import java.io.Serializable;
import java.lang.invoke.SerializedLambda;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class EnumUtils {
    private static final Map<Class<?>, SerializedLambda> CLASS_LAMBDA_CACHE = new ConcurrentHashMap<>();


    /**
     * 传入枚举get方法和值查询对应枚举,查询不到返回null
     * @param fn 枚举对应get方法
     * @param val 值
     * @return 枚举
     */
    @SuppressWarnings("unchecked")
    public static <E,M,C> E getByValue(Func1<E,M> fn, C val){
        SerializedLambda serializedLambda = getSerializedLambda(fn);
        String implClass = serializedLambda.getImplClass();
        String className = StringUtils.replace(implClass, "/", ".");

        Class<E> aClass = null;
        try {
            aClass = (Class<E>) Class.forName(className);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }

        return Arrays.stream(aClass.getEnumConstants()).filter(e -> fn.getEnum(e).equals(val)).findAny().orElse(null);
    }

    /** 传入枚举get方法和值判断对应枚举是否存在
     * @param fn  枚举对应get方法
     * @param val 值
     * @return  Boolean
     */
    public static <E,M,C> Boolean existByValue(Func1<E,M> fn, C val){
       return getByValue(fn,val) != null;

    }

    private static SerializedLambda getSerializedLambda(Serializable fn) {
        SerializedLambda lambda = CLASS_LAMBDA_CACHE.get(fn.getClass());
        // 先检查缓存中是否存在
        if (lambda == null) {
            try {
                // 提取SerializedLambda并缓存
                Method method = fn.getClass().getDeclaredMethod("writeReplace");
                method.setAccessible(Boolean.TRUE);
                lambda = (SerializedLambda) method.invoke(fn);
                CLASS_LAMBDA_CACHE.put(fn.getClass(), lambda);
            } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
        return lambda;
    }
}
